package com.itvita.code.generator.engine;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itvita.code.generator.constant.TemplateConstVal;
import com.itvita.code.generator.entity.model.CreateInfo;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * @Time: 2021/1/22 9:18 上午
 * @author: liu.q [916000612@qq.com]
 * @des: beetl模板引擎
 */
@Slf4j
public class BeetlTemplateEngine extends AbstractTemplateEngine {

    private GroupTemplate groupTemplate;

    @Override
    public AbstractTemplateEngine init(CreateInfo createDto) {
        super.init(createDto);
        try {
            ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("templates");
            Configuration cfg = Configuration.defaultConfiguration();
            this.groupTemplate = new GroupTemplate(resourceLoader, cfg);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return this;
    }

    @Override
    public void writer(TemplateConfig templateConfig, String outputFile, String filePath) {
        mkdirs(outputFile);
        Template template = groupTemplate.getTemplate(filePath);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
            template.binding(JSON.parseObject(JSON.toJSONString(templateConfig), Map.class));
            template.renderTo(fileOutputStream);
            fileOutputStream.close();
            log.debug("生成成功:{}", outputFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建输出目录
     */
    private String mkdirs(String outputFile) {
        String path = outputFile.substring(0, outputFile.lastIndexOf(File.separator));
        File dir = new File(path);
        if (!dir.exists()) {
            boolean result = dir.mkdirs();
            if (result) {
                log.debug("创建目录： [" + outputFile + "]");
            }
        }
        return outputFile;
    }
}
